/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import FolderStackModule, { FoldStatus } from '../turbo/FolderStackModule';
import { DeviceEventEmitter, Dimensions, EmitterSubscription } from 'react-native';

const FoldUtil = FolderStackModule!;
// 上下折叠与左右折叠高宽比的阈值，大于1.3为上下折叠，小于1.3为左右折叠
const THRESHOLD = 1.3;
// 小屏幕的宽度阈值
export const SMALL_SCREEN_WIDTH = 500;

const foldDidChangeEvent = 'foldStatusChange';
let listener: EmitterSubscription = null;

export const Fold = {
  getFoldCreaseRegion(): number[][] {
    return FoldUtil?.getFoldCreaseRegion();
  },
  isFoldable(): boolean {
    return FoldUtil?.isFoldable();
  },
  isHorizontalFold(isPortraitOrientation: boolean): boolean {
    const screen = Dimensions.get('screen');
    // 计算高宽比
    const aspectRatio = screen.height / screen.width;
    if (isPortraitOrientation) {
      return aspectRatio > THRESHOLD;
    } else {
      return aspectRatio < 1 / THRESHOLD;
    }
  },
  getFoldStatus(): FoldStatus {
    return FoldUtil?.getFoldStatus();
  },
  addFoldListener(cb: (foldStatus: FoldStatus) => void): void {
    FoldUtil?.addFoldListener();
    listener = DeviceEventEmitter.addListener(
      foldDidChangeEvent,
      (foldStatus: FoldStatus) => {
        cb(foldStatus);
      }
    );
  },
  removeFoldListener(): void {
    FoldUtil?.removeFoldListener();
    if (!listener) {
      return;
    }
    listener.remove();
    listener = null;
  },
};
